package com.telecom.at.front;

import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

import com.telecom.at.db.dac.Dac;
import com.telecom.at.db.model.Doc;


@WebServlet("/front/DownloadDoc")
public class DownloadDoc extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String userAgent = request.getHeader("User-Agent");
		System.out.println(userAgent);
		long id = 0;
		try{
			id = Long.parseLong(request.getParameter("id"));
		}catch(Exception e){
		}
		Doc doc = Dac.getInstance().getDoc(id);
		if(doc != null){
			response.setContentType("application/octet-stream");
			if(userAgent.indexOf("Trident") != -1 || userAgent.indexOf("MSIE") != -1)
				response.addHeader("Content-Disposition", "attachment; filename="+new String(doc.getName().getBytes("GBK"),"ISO-8859-1"));
			else
				response.addHeader("Content-Disposition", "attachment; filename="+new String(doc.getName().getBytes("UTF-8"),"ISO-8859-1"));
			FileInputStream fis = new FileInputStream(
					request.getServletContext()
					.getRealPath(doc.getFullName()));
			IOUtils.copy(fis, response.getOutputStream());
			fis.close();
		}		
	}
}
